<template>
  <div class="flex flex-column " >
    <div class="home-table-area bg-white">
      <el-row class="float-right" style="z-index:999">
          <el-button  type="primary" @click="insertPerson" v-show="activeName==='first'&&isAddAdmin===true">添加管理员</el-button>
          <el-button  type="primary" @click="insertUsers" v-show="activeName==='second'&&isAddGroup===true">添加角色</el-button>
      </el-row>
      <el-tabs v-model="activeName">
        <el-tab-pane label="管理员管理" :disabled="first"  name="first">
          <div class="hm-select-area align-center bg-white font-14"  v-if="isAdminList">
            <el-input class="hta-input" placeholder="搜索姓名等关键字" v-model="searchObj.keywords">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <el-button type="primary" @click="getUserList">搜索</el-button>
            <span style="margin-left: 100px;">角色</span>
            <el-select v-model="searchObj.group_id" placeholder="请选择" class="hm-select" @change="searchType" clearable>
              <el-option
                v-for="item in tableDatas"
                :key="item.group_id"
                :label="item.group_name"
                :value="item.group_id">
              </el-option>
            </el-select>
          </div>
           <el-table  :data="tableData"  v-if="isAdminList" :header-cell-style="{background:'#F7F7F7',color:'#101010', fontWeight: 'normal'}">
            <el-table-column type="index" width="60" label="序号" header-align="center" align="center">
              <template slot-scope="scope">
                <div>{{(searchObj.page - 1) * searchObj.page_num + scope.$index + 1}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="账号" header-align="center" align="center"></el-table-column>
            <el-table-column prop="true_name" label="姓名" header-align="center" align="center"></el-table-column>
            <el-table-column prop="phone" label="联系方式" header-align="center" align="center"></el-table-column>
            <el-table-column prop="group_name" label="角色" header-align="center" align="center"></el-table-column>
            <el-table-column prop="parking_lot_name" label="停车场" header-align="center" align="center"></el-table-column>
            <el-table-column header-align="center" align="center" label="操作">
              <template slot-scope="scope">
                <el-button type='text' @click="editUsernameInfo(scope.row)">编辑</el-button>
                <el-button type='text'  @click="delUsernameInfo(scope.row.admin_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            class="hm-page"
            background
            layout="prev, pager, next"
            :total="total" @current-change="sizeChange">
          </el-pagination>
        </el-tab-pane>  
        <el-tab-pane label="角色管理" :disabled="second" name="second">
          <el-table :data="tableDatas" v-if="isGroupList" :header-cell-style="{background:'#F7F7F7',color:'#101010', fontWeight: 'normal'}" >
            <el-table-column type="index" width="60" label="序号">
              <template slot-scope="scope">
                <div>{{(searchObj.page - 1) * searchObj.page_num + scope.$index + 1}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="group_name" label="角色名称" header-align="center" align="center"></el-table-column>
            <el-table-column prop="group_desc" label="描述" header-align="center" align="center"></el-table-column>
            <el-table-column label="创建时间" header-align="center" align="center" width="200">
              <template slot-scope="scope">
                  {{dateFormat(scope.row.created_at)}}
              </template>
            </el-table-column>
            <el-table-column label="更新时间" header-align="center" align="center">
              <template slot-scope="scope">
                  {{dateFormat(scope.row.updated_at)}}
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" label="操作">
              <template slot-scope="scope">
                <el-button type='text' v-if="isUpdateGroup" @click="editInfo(scope.row)">编辑</el-button>
                <el-button type='text' v-if="isDeleteGroup" @click="delUserInfo(scope.row.group_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            class="hm-page"
            background
            layout="prev, pager, next"
            :total="totals" @current-change="sizeChanges">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="权限管理" :disabled="third" name="third">  
          <div >
            <el-tree
              ref="tree"
              default-expand-all
              :data="treeData"
              :props="defaultProps">
            </el-tree>
          </div>
        </el-tab-pane> 
      </el-tabs>         
    </div>
      <!-- 添加管理员弹框 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="45%"
        :before-close="handleClose">
        <el-form :model="addForm" ref="addForm" label-width="120px" >
          <el-row>
            <el-col :span="16">
              <el-form-item label="账号">  
                <el-input v-model="addForm.username" placeholder="请输入账号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="姓名">  
                <el-input v-model="addForm.true_name" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="联系方式">  
                <el-input v-model="addForm.phone" placeholder="请输入手机号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="角色">  
                <el-select v-model="addForm.group_id" placeholder="请选择">
                  <el-option
                    v-for="item in tableDatas"
                    :key="item.group_id"
                    :label="item.group_name"
                    :value="item.group_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="停车场">  
                <el-checkbox-group v-model="parking_lot_id" v-for="item in parkList" @change="parkChange" :key="item.parking_lot_id">
                  <el-col :span="12">
                    <el-checkbox :label="item.parking_lot_id.toString()" >{{item.parking_lot_name}}</el-checkbox>
                  </el-col>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="text-align:center">
            <el-button type="primary" v-if="title==='添加管理员'" @click="readyress"><span style="margin:0 30px">确定</span></el-button>
            <el-button type="primary" v-if="title==='编辑管理员'" @click="editusernameress"><span style="margin:0 30px">确定</span></el-button>
          </div>
        </el-form>  
      </el-dialog>
       <!-- 角色管理弹框 -->
      <el-dialog
        :title="titles"
        :visible.sync="dialogVisibleInsertUser"
        width="50%"
        :before-close="handleCloseInsertUser">
        <el-form ref="insertUser" :model="insertUser" label-width="120px">
            <el-row>
              <el-col :span="20">
                <el-form-item label="角色名称：">
                  <el-input v-model="insertUser.group_name" placeholder="请输入角色名称"></el-input>
                </el-form-item>
              </el-col>  
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="职能描述：">
                  <el-input v-model="insertUser.group_desc" placeholder="请输入角色描述"></el-input>
                </el-form-item>
              </el-col>  
            </el-row>
            <el-row v-if="isTree">
              <el-col :span="24">
                <el-form-item label="分配权限：">
                  <div class="tree-class" style="height:300px;overflow-y:auto">
                    <el-tree
                      ref="tree"
                      :data="treeData"
                      :props="defaultProps"
                      :default-checked-keys="auth_ids"
                      show-checkbox
                      node-key="auth_id"
                      accordion>
                    </el-tree>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
        <div style="text-align:center">
          <el-button type="primary" v-if="titles==='添加角色'" @click="deterress"><span style="margin:0 30px;">确定</span></el-button>
          <el-button type="primary" v-if="titles==='编辑角色'" @click="editress"><span style="margin:0 30px;">确定</span></el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      isTree:false,
      treeData:[],
      first:true,
      second:true,
      third:false,
      isAdminList:false,
      isAddAdmin:false,
      isGroupList:false,
      isDeleteGroup:false,
      isUpdateGroup:false,
      isAddGroup:false,
      activeName:'third',
      insertUser:{
        group_name:'',
        group_desc:'',
        auth_ids:'',
        group_id:''
      },
      auth_ids:[],
      defaultProps:{
        children: 'children',
        label: 'name'
      },
      searchObj: {
        page: 1,
        page_num: 10,
        keywords:'',
        admin_id:'',
        group_id:''        
      },
      searchObjs:{
        page: 1,
        page_num: 10
      },
      addForm:{
        username:'',
        true_name:'',
        phone:'',
        group_id:'',
        parking_lot_id:''
      },
      parking_lot_id:[],
      parkList:[],
      dialogVisible:false,
      dialogVisibleUser:false,
      dialogVisibleInsertUser:false,
      total: 10,
      totals: 1,
      title:'添加管理员',
      titles:'添加角色',
      tableData: [],
      tableDatas: [],
      groupId: '',
      admin_id:'',
      vueAuthList:[]
    }
  },
  mounted () {
    this.admin_id = this.$store.state.adminId
    this.vueAuthList = this.$store.state.vueAuthList
    let that = this
    this.vueAuthList.forEach(function(res){
      if(res==='adminList'){
        that.first = false
        that.activeName = 'first'
        that.isAdminList = true
      }
      if(res==='addAdmin'){
        that.isAddAdmin = true
      }
      if(res==='groupList'){
        that.isGroupList = true
        that.activeName = 'second'
        that.second = false
        if(that.first===false){
          that.activeName = 'first'
        }
      }
      if(res==='deleteGroup')
        that.isDeleteGroup = true
      if(res==='updateGroup')
        that.isUpdateGroup = true
      if(res==='addGroup')
        that.isAddGroup = true
    })
    this.getRole()
    this.getParkingLotListByLoginId()
    this.getAuthListAll()
    this.getGroup()
  },
  methods: {
    //停车场列表
    getParkingLotListByLoginId(){
      this.$api.parkingLotListByLoginId({admin_id:this.admin_id}).then(res => {
        this.parkList = res
      })
    }, 
    getAuthListAll(){
      this.$api.authListAll().then(res => {
        this.treeData = res
      })
    },
    //添加管理员
    insertPerson(){
      this.title = "添加管理员"
      this.dialogVisible = true
    },
    // 添加角色
    insertUsers(){
      this.titles = '添加角色'
      this.isTree = false
      this.dialogVisibleInsertUser = true
    },
    // 确定
    deterress(){
      if (!this.insertUser.group_name) {
        this.$message.error('请输入角色名称')
        return false
      }
      if (!this.insertUser.group_desc) {
        this.$message.error('请输入角色描述')
        return false
      }
      this.$api.addGroup({group_name:this.insertUser.group_name,group_desc:this.insertUser.group_desc}).then(res => {
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.getUserLists()
        this.handleCloseInsertUser()
      })
    },
    // 停车场的值[]
    parkChange(val){
      // console.log(val)
      if(val.length>1){
        let arr = [];
        for(let i=0;i<val.length;i++) {
          if(i===val.length-1){
            arr+=val[i]
          }  
          else{
            arr+=val[i]+","
          }  
        }
        this.addForm.parking_lot_id = arr
      }
      else if(val.length===1){
        this.addForm.parking_lot_id = val[0];
      }else {
        this.addForm.parking_lot_id = '';
      }
    },
    // 添加管理员-关闭添加弹框
    handleClose(){
      this.dialogVisible = false
      this.addForm = {
        username:'',
        true_name:'',
        phone:'',
        group_id:'',
        parking_lot_id:''
      }
      this.parking_lot_id = []
    },
    // 角色管理-添加角色关闭弹框
    handleCloseInsertUser(){
      this.dialogVisibleInsertUser = false
      this.insertUser = {
        group_name:'',
        group_desc:'',
      }
      this.auth_ids = []
      if(this.titles === '编辑角色'){
        this.$refs.tree.setCheckedKeys([])
      }
    },
    // 添加管理员-确定
    readyress(){
      if (!this.addForm.username) {
        this.$message.error('请输入账号')
        return false
      }
      if (!this.addForm.true_name) {
        this.$message.error('请输入姓名')
        return false
      }
      if (!this.addForm.phone) {
        this.$message.error('请输入联系方式')
        return false
      }
      if(!this.addForm.group_id){
        this.$message.error('请选择角色')
        return false
      }
      if(!this.addForm.parking_lot_id){
        this.$message.error('请选择至少一个停车场')
        return false
      }
      this.$api.addAdmin(this.addForm).then(res=>{
        this.$message({
          type:'success',
          message:'添加成功',
          duration: 800,
          onClose: () => {
            this.getUserList()
            this.handleClose()
          }
        })
      })
    },
    // 角色管理-编辑
    editInfo(item){
      // console.log(item)
      this.insertUser.group_name = item.group_name
      this.insertUser.group_desc = item.group_desc
      this.insertUser.group_id = item.group_id
      this.auth_ids = item.auth_ids.split(",")
      this.titles = '编辑角色'
      this.isTree = true
      this.dialogVisibleInsertUser = true
    },
    editress(){
      if (!this.insertUser.group_name) {
        this.$message.error('请输入角色名称')
        return false
      }
      if (!this.insertUser.group_desc) {
        this.$message.error('请输入角色描述')
        return false
      }
      let getCheck = this.$refs.tree.getCheckedNodes()
      let number = 0
      let that = this
      this.insertUser.auth_ids = ''
      getCheck.forEach(function (check) {
        // console.log(check)
        number++
        if(number===getCheck.length){
          that.insertUser.auth_ids+=check.auth_id
        }else{
          that.insertUser.auth_ids+=check.auth_id+","
        }  
      })
      this.$api.updateGroup(this.insertUser).then(res => {
        this.$message({
          type: 'success',
          message: '编辑成功',
          duration: 800,
          onClose: () => {
            this.getGroup()
            this.handleCloseInsertUser()
          }
        })
      })
    },
    // 编辑管理员
    editUsernameInfo(val){
      // console.log(val)
      this.title = '编辑管理员'
      this.addForm.username = val.username 
      this.addForm.true_name = val.true_name 
      this.addForm.phone = val.phone 
      this.addForm.group_id = val.group_id 
      this.addForm.admin_id = val.admin_id 
      this.parking_lot_id = val.parking_lot_id.split(",")
      this.dialogVisible = true
    },
    // 编辑管理员-确定
    editusernameress(){
      this.parkChange(this.parking_lot_id)
      if (!this.addForm.username) {
        this.$message.error('请输入账号')
        return false
      }
      if (!this.addForm.true_name) {
        this.$message.error('请输入姓名')
        return false
      }
      if (!this.addForm.phone) {
        this.$message.error('请输入联系方式')
        return false
      }
      if(!this.addForm.group_id){
        this.$message.error('请选择角色')
        return false
      }
      if(!this.addForm.parking_lot_id){
        this.$message.error('请选择至少一个停车场')
        return false
      }
      this.$api.editAdmin(this.addForm).then(res=>{
        this.$message({
          type:'success',
          message:'编辑成功',
          duration: 800,
          onClose: () => {
            this.getRole()
            this.handleClose()
          }
        })
      })
    },
    // 删除管理员
    delUsernameInfo(val){
      this.$confirm('此操作将删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deleteAdmin({admin_id:val}).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功',
            duration: 2000
          })
          this.getRole()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });  
    },
    // 删除角色
    delUserInfo(group_id){
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deleteGroup({group_id:group_id}).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功',
            duration: 500
          })
          this.getGroup()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });  
    },
    // 上面角色 搜索
    searchType (val) {
      // console.log(val)
      this.getUserList()
    },
    getUserList() {
      this.searchObj.page = 1
      this.getRole()
    },
    getUserLists(){
      this.searchObjs.page = 1
      this.getGroup()
    },
    sizeChange (val) {
      this.searchObj.page = val
      this.getRole()
    },
    sizeChanges (val) {
      this.searchObjs.page = val
      this.getGroup()
    },
    getRole(){
      this.searchObj.admin_id = this.admin_id
      this.$api.adminList(this.searchObj).then(res => {
        this.tableData = res.data
        this.total = res.page_info.total
      })
    },
    getGroup(){
      this.$api.groupList(this.searchObjs).then(res => {
        this.tableDatas = res.data
        this.totals = res.page_info.total
      })
    },  
    dateFormat (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
      date = new Date(date * 1000)
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    }
  }
}
</script>

<style scoped>
  .flex >>>.el-tabs__nav-wrap::after,.flex >>>.el-tabs__active-bar.is-top{
    width: 0%!important;
  }
  .flex >>>.el-tabs__item.is-top.is-active{
      font-size:18px;
  }
  .hta-input {
    width: 260px;
    margin-right: 23px;
  }
  .tree-class >>>.el-icon-caret-right:before{
    content:'';
  }
  .hometable{
    padding: 24px 45px 24px 24px;
}
  /* 隐藏第一级超级管理者的前面那个框 */
  /* .tree-class > >>>.el-tree > .el-tree-node.is-focusable >.el-tree-node__content >.el-checkbox{
    display: none!important;
  } */
</style>
